'use strict'

let { user, issue, options, questionnaire, statistical } = require('../models')


// 登录界面
let login_fn = async (ctx, next) => {
    ctx.render('login.html');
};

// 注册界面
let register_fn = async (ctx, next) => {
    ctx.render('register.html')
};

// 首页
let index_fn = async (ctx, next) => {
    let userName = ctx.session.userName
    let userId = ctx.session.userId
    let obj = {
        userName,
        userId
    }
    ctx.render('index.html', obj)
}

// 添加问卷页面
let addQuestionnaire_fn = async (ctx, next) => {
    let obj = {
        userName: ctx.session.userName,
        userId: ctx.session.userId
    }
    ctx.render('addQuestionnaire.html', obj)
}

// 登录验证
let loginDeno_fn = async (ctx, next) => {
    let username = ctx.request.body.username
    let password = ctx.request.body.password
    let res = ''

    if (username === "" || password === "") {
        res = { code: 500, msg: '用户名或密码不能为空' }
    } else {
        let u = await user.findOne({ where: { username: username } })
        if (u === null) {
            res = { code: 500, msg: '用户不存在,请点击注册!' }
        } else {
            if (username === u.username && password === u.password) {
                ctx.session.userName = u.username,
                    ctx.session.userId = u.id
                res = { code: 200, msg: '登录成功' }
            }
            else {
                res = { code: 500, msg: '用户名或密码不正确!' }
            }
        }
    }

    ctx.body = res;
}

// 注册验证
let registerDeno_fn = async (ctx, next) => {
    let username = ctx.request.body.username
    let password = ctx.request.body.password
    let confirmpassword = ctx.request.body.confirmpassword
    let res = ''

    if (username === "" || password === "" || confirmpassword === "") {
        res = { code: 500, msg: '用户名或密码不能为空!' }
    } else {
        let u = await user.findOne({ where: { username: username } });
        if (u === null) {
            if (password === confirmpassword) {
                user.create({ username: username, password: password })
                res = { code: 200, msg: '注册成功,请前往登录' }
            } else {
                res = { code: 500, msg: '两次输入的密码不正确,请核对后重新输入!' }
            }
        } else {
            res = { code: 500, msg: '用户已存在请前往登录' }
        }
    }

    ctx.body = res

}

//登出验证
let logout_fn = async (ctx, next) => {
    ctx.session = null
    let res = { code: 200 }
    ctx.body = res
}

// 添加问卷页面提交按钮验证
let addQuestionnaireDeno_fn = async (ctx, next) => {
    let data = ctx.request.body
    let themename = data.questionnaireText;
    let userId = data.userId
    let res = ''

    //先查找问卷主题存不存在
    let quest = await questionnaire.findOne({ where: { themename: themename, userId: userId } })
    if (quest !== null) {
        res = { code: 500, msg: '当前用户已创建同名的问卷主题,请换一个吧' }
    } else {
        //不存在 插入问卷主题 
        await questionnaire.create({ themename: themename, userId: userId });
        // 在问卷表中 根据插入的问卷主题查找问卷主题Id 
        let quest2 = await questionnaire.findOne({ where: { themename: themename, userId: userId } })
        // 插入问卷的题目 
        for (let list of data.list) {
            // 插入数据库
            await issue.create({ issuename: list.title, questionnaireId: quest2.id })
            // 插入题目的选项
            for (let op of list.options) {
                // 在问题表中 根据问卷Id与题目名字查找题目Id
                let isu = await issue.findOne({ where: { issuename: list.title, questionnaireId: quest2.id } })
                // 插入数据库
                await options.create({ optionname: op.op, issueId: isu.id })
            }
        }
        res = { code: 200, msg: '创建问卷成功!' }
    }

    ctx.body = res
}

// 首页响应时传递数据
let indexInit_fn = async (ctx, next) => {
    let questMsg = []
    function getTime(datas) {
        //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let date = new Date(datas);
        let Y = date.getFullYear() + "-";
        let M =
            (date.getMonth() + 1 < 10
                ? "0" + (date.getMonth() + 1)
                : date.getMonth() + 1) + "-";
        let D = date.getDate() + " ";
        let h = date.getHours() + ":";
        let m = date.getMinutes() + ":";
        let s = date.getSeconds();
        return Y + M + D + h + m + s;
    }
    //查找所有问卷主题 创建问卷的用户的用户名 创建问卷的时间 
    // 查找所有问卷主题名称
    let questAll = await questionnaire.findAll();
    // 插入数组
    for (let item of questAll) {
        // 根据userId查找用户名
        let u = await user.findOne({ where: { id: item.userId } })
        questMsg.push({ questId: item.id, themename: item.themename, userName: u.username, createAt: getTime(parseInt(item.createAt)) });
    }

    ctx.body = questMsg
}

// 分享页面
let share_fn = async (ctx, next) => {
    let obj = {
        userName: ctx.session.userName,
        userId: ctx.session.userId
    }
    ctx.render('answer.html', obj)
}
// 分享验证 保存主题Id
let shareDeno_fn = async (ctx, next) => {
    ctx.session.questId = ctx.request.body.questId;
    let res = { code: 200 }
    ctx.body = res
}

// 问题页面响应时传递数据
let answerInit_fn = async (ctx, next) => {
    let questId = ctx.session.questId
    let userId = ctx.session.userId
    let obj = {
        userId,
        questId,
        themename: '',
        issueList: []
    }
    // 根据问卷Id查找 该问卷的主题
    let questMsg = await questionnaire.findOne({ where: { id: questId } }) //当前问卷的信息
    // 问卷主题
    obj.themename = questMsg.themename
    // 根据问卷Id 在问题表中查找 该问卷的所有题目 
    let issueArr = await issue.findAll({ where: { questionnaireId: questId } })
    for (let i of issueArr) {
        // 根据查找的题目 查找题目Id 
        let issueId = await issue.findOne({ where: { issuename: i.issuename } })
        obj.issueList.push({ issueId: issueId.id, isssueText: i.issuename, optionList: [] }) // 问卷题目 // 题目Id  // 题目选项[] 
    }
    for (let op of obj.issueList) {
        // 并用题目Id查找该题目的所有选项 选项Id
        let optionArr = await options.findAll({ where: { issueId: op.issueId } })
        for (let o of optionArr) {
            op.optionList.push({ optionId: o.id, optionText: o.optionname, checked: false })
        }
    }
    ctx.body = obj
}

// 提交问卷
let answerAdd_fn = async (ctx, next) => {
    let data = ctx.request.body
    let res = ''
    console.log(data);
    data.issueList.forEach(item => {
        if (item.optionList.length < 1) {
            res = { code: 500, msg: '有选项没有填选,请重新填选！' }
        } else {
            // 在统计表中插入 用户Id 问卷Id 问题Id 选项Id
            for (let op of item.optionList) {
                // console.log('用户Id--' + data.userId + '---' + '问卷Id--' + data.questId + '--' + '问题Id--' + item.issueId + '--' + '选项Id--' + op.optionId);
                statistical.create({ userId: data.userId, questionnaireId: data.questId, issueId: item.issueId, optionId: op.optionId });
            }
            res = { code: 200, msg: '提交成功!' }
        }
    });

    ctx.body = res
}

// 提交完成页面
let submitSucced_fn = async (ctx, next) => {
    let obj = {
        userName: ctx.session.userName,
        userId: ctx.session.userId
    }
    ctx.render('submitSucced.html', obj)
}

// 问题页面 
let answer_fn = async (ctx, next) => {
    let userName = ctx.session.userName || ''
    let userId = ctx.session.userId || ''
    let obj = {
        userName,
        userId
    }
    if (userId === "") {
        ctx.render('login.html')
    } else {
        ctx.render('answer.html', obj)
    }
}

module.exports = {
    '/': ['get', login_fn],
    '/register': ['get', register_fn],
    '/index': ['get', index_fn],
    '/addQuestionnaire': ['get', addQuestionnaire_fn],
    '/loginDeno': ['post', loginDeno_fn],
    '/registerDeno': ['post', registerDeno_fn],
    '/addQuestionnaireDeno': ['post', addQuestionnaireDeno_fn],
    '/logout': ['post', logout_fn],
    '/indexInit': ['post', indexInit_fn],
    '/share': ['get', share_fn],
    '/shareDeno': ['post', shareDeno_fn],
    '/answerInit': ['get', answerInit_fn],
    '/answerAdd': ['post', answerAdd_fn],
    '/answer': ['get', answer_fn]
}
